#include "AvatarRequestTask.h"
#include "../packages/avatar/CliIcqIconRequest.h"
#include "../OscarProtData.h"
#include "../../../core/Impp.h"

namespace Impp
{

AvatarRequestTask::AvatarRequestTask(Oscar* oscar, Buddy* buddy, const ActionId & id) :
	Task(TASK_AVATAR_REQUEST,oscar,TASK_HANDLE_REQUESTID,0,(time_t)20), buddy(buddy),requestSent(false),error(false),actionId(id)
{

	if(!oscar->serviceConnectionRequested() && !oscar->getServiceConnection()->isConnected()){
		oscar->requestServiceConnection();
	}else{
		if(oscar->getServiceConnection()->isConnected()){
			sendRequest();
		}
	}

}

void AvatarRequestTask::sendRequest(){

	if(OscarProtData* protData = dynamic_cast<OscarProtData*>(buddy->getProtocolData())){
		if(protData->getUserInfo()->avatar.hasLng != 0 && protData->getUserInfo()->avatar.id == 0x01){
			wxLogTrace(wxT("AVATAR"),wxT("send Avatar request"));
			OscarServerCon* service = oscar->getServiceConnection();
			dword reqId = service->nextRequestId();
			service->sendPackage(DATA,new CliIcqIconRequest(buddy,reqId));
			handle = reqId;
		}else{
			wxLogTrace(wxT("AVATAR"),wxT("AvatarRequestTask::sendRequest: Buddy has no AvaData or id was wrong"));
			error=true;
			Impp::exemplar()->processAvararRequestError(actionId);
		}
	}else{
		Impp::exemplar()->processAvararRequestError(actionId);
		wxLogError(wxT("AvatarRequestTask::sendRequest: Buddy has noiOscarProtData, Buddy shoud be a ICQ Buddy!"));
	}
	requestSent=true;
}

AvatarRequestTask::~AvatarRequestTask()
{
}

void AvatarRequestTask::timedOut(){
	if(error){
		wxLogTrace(wxT("AVATAR"),wxT("AvatarRequestTask::timedOut: failed because Buddy had no Avatardata!"));
	}else{
		wxLogTrace(wxT("AVATAR"),wxT("AvatarRequestTask::timedOut: failed because of a timeout!"));
		Impp::exemplar()->processAvararRequestError(actionId);
	}
}

bool AvatarRequestTask::checkForTimeOut(const time_t & now){
	if(error || Task::checkForTimeOut(now)){
		return true;
	}
	if(!requestSent && oscar->getServiceConnection()->isConnected()){
		sendRequest();
	}
	return false;
}

ActionId AvatarRequestTask::getActionId()
{
	return actionId;
}

}
